import os
import re
import winreg
import zipfile
import webbrowser
import requests
from pathlib import Path
from .settings import PATH


base_url = 'http://npm.taobao.org/mirrors/chromedriver/'
version_re = re.compile(r'^[1-9]\d*\.\d*.\d*')  # 匹配前3位版本号的正则表达式


def get_chrome_version():
    """通过注册表查询chrome版本"""
    try:
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Google\\Chrome\\BLBeacon')
        value, t = winreg.QueryValueEx(key, 'version')
        return version_re.findall(value)[0]  # 返回前3位版本号
    except Exception as e:
        # 没有安装chrome浏览器
        return "1.1.1"


def get_chrome_driver_version():
    """查询Chromedriver版本"""
    if not PATH.driver_exe.is_file():
        return "0.0.0"

    version = os.popen(f'{PATH.driver_exe} --version').read()
    try:
        version = version.split(' ')[1]
        version = ".".join(version.split(".")[:-1])
        return version
    except Exception as e:
        return "0.0.0"


def get_latest_chrome_driver(version, print_log):
    # 获取该chrome版本的最新driver版本号
    url = f"{base_url}LATEST_RELEASE_{version}"
    latest_version = requests.get(url).text
    print_log(f"与当前chrome匹配的最新chromedriver版本为: {latest_version}")
    # 下载chromedriver
    print_log("开始下载chromedriver...")
    download_url = f"{base_url}{latest_version}/chromedriver_win32.zip"
    file = requests.get(download_url)
    if file.status_code == 404:
        # 如果上面的方法获取到最新版本无法下载，就使用这个方法
        print_log("下载失败，正在尝试通道二....")
        res = requests.get("http://npm.taobao.org/mirrors/chromedriver/")
        if res.status_code != 200:
            raise Exception("无法获取驱动网页！")
        ver = re.compile(f"/mirrors/chromedriver/{version}.[0-9]+")
        url = ver.findall(res.text)
        if len(url) == 0:
            raise Exception("没有找到匹配版本的驱动！")
        url = url[0]
        download_url = f"http://npm.taobao.org{url}/chromedriver_win32.zip"
        file = requests.get(download_url)

    with open(PATH.driver / "chromedriver.zip", 'wb') as zip_file:  # 保存文件到脚本所在目录
        zip_file.write(file.content)
    print_log("下载完成.")
    # 解压
    f = zipfile.ZipFile(PATH.driver / "chromedriver.zip", 'r')
    for file in f.namelist():
        f.extract(file, PATH.driver)
    print_log("解压完成.")


def check_chrome_driver_update(print_log=print):
    print_log('正在检查驱动环境...')
    chrome_exe_1 = Path("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")
    chrome_exe_2 = Path("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe")
    if not (chrome_exe_1.is_file() or chrome_exe_2.is_file()):
        print_log('系统未安装chrome浏览器，请在弹出的浏览器窗口下载安装后再使用本软件。')
        webbrowser.open("https://www.google.com/intl/zh-CN/chrome/")
        return False
    chrome_version = get_chrome_version()
    print_log(f'当前chrome版本: {chrome_version}')
    driver_version = get_chrome_driver_version()
    print_log(f'当前chromedriver版本: {driver_version}')
    if chrome_version == driver_version:
        print_log("驱动环境检测完成!版本兼容，无需更新.\n")
        return True
    print_log("chromedriver版本与chrome浏览器不兼容，更新中>>>")
    try:
        get_latest_chrome_driver(chrome_version, print_log)
        driver_version = get_chrome_driver_version()
        print_log(f"chromedriver更新成功!当前chromedriver版本: {driver_version}\n")
        return True
    except requests.exceptions.Timeout:
        print_log("chromedriver下载失败，请检查网络后重试！\n")
    except Exception as e:
        print_log(f"chromedriver更新失败，原因为: {e}\n")
    return False


if __name__ == "__main__":
    check_chrome_driver_update()
